package top.infopub.mgr.cap.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.infopub.dto.cap.ContractMortgageDto;
import top.infopub.enums.cap.CapProcessDetailTypeEnum;
import top.infopub.enums.mkt.ProProcesssStatusEnum;
import top.infopub.enums.mkt.ProjectFileTypeEnum;
import top.infopub.generic.GenericDao;
import top.infopub.generic.GenericServiceImpl;
import top.infopub.mgr.cap.dao.ContractGuarantyDao;
import top.infopub.mgr.cap.dao.ContractMortgageDao;
import top.infopub.mgr.cap.dao.ContractMortgageDetailDao;
import top.infopub.mgr.cap.domain.ContractMortgageDomain;
import top.infopub.mgr.cap.jsonvo.ContractMortgageJsonVo;
import top.infopub.mgr.cap.service.CapProcessManageService;
import top.infopub.mgr.cap.service.ContractMortgageService;
import top.infopub.mgr.cap.vo.ContractMortgageVo;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.service.OAFlowService;
import top.infopub.mgr.mkt.dao.ProjectAttachmentDao;
import top.infopub.mgr.mkt.service.SetupProService;
import top.infopub.model.cap.*;
import top.infopub.model.mkt.ProjectAttachment;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.tdp.sys.service.CodeGeneratorConfigService;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ContractMortgageServiceImpl extends GenericServiceImpl<ContractMortgage, String> implements ContractMortgageService {

    @Autowired
    private ContractMortgageDao contractMortgageDao;
    @Autowired
    private ContractMortgageDetailDao contractPledgeDetailDao;
    @Autowired
    private ContractMortgageDetailDao contractMortgageDetailDao;
    @Autowired
    private ProjectAttachmentDao projectAttachmentDao;
    @Autowired
    private SetupProService setupProService;
    @Autowired
    private OAFlowService oaFlowService;
    @Autowired
    private CodeGeneratorConfigService codeGeneratorConfigService;

    @Autowired
    private CapProcessManageService capProcessManageService;

    @Autowired
    private ContractGuarantyDao contractGuarantyDao;

    @Override
    public GenericDao<ContractMortgage, String> getDao() {
        return contractMortgageDao;
    }

    @Override
    public Page<ContractMortgageDomain> selectByDomainWhere(Page<ContractMortgageDomain> page, ContractMortgageVo contractMortgageVo) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        return (Page<ContractMortgageDomain>)contractMortgageDao.selectByDomainWhere(contractMortgageVo);
    }

    @Override
    public ContractMortgageJsonVo queryDetailById(String id) {
        String codes=codeGeneratorConfigService.generatorCode("cap_contract_mortgage");
        ContractMortgageJsonVo jsonVo = new ContractMortgageJsonVo();
        /*判断id是否为空,为空就显示项目名称下拉框,并显示金融机构下拉框，由项目名称带出来*/
        if(StringUtils.isEmpty(id)){
           List<FinancingName> financingNames= contractGuarantyDao.queryListFinancingName();
           for(FinancingName financingName:financingNames){
                financingName.setCodes(codes);
//              List<ContractGuaranty> institutions= contractGuarantyDao.selectInstitutions(financingName.getProCode());
//               jsonVo.setInstitutions(institutions);
           }
           jsonVo.setFinancingNames(financingNames);
        }else{
            /*融资基本信息*/
            ContractMortgageDto dto = contractMortgageDao.queryDetailById(id);
            jsonVo.setInfo(dto);
            /*担保单位信息*/
            List<ContractMortgageDetail> details = contractMortgageDetailDao.queryListByContractMorId(dto.getId());
            jsonVo.setDetails(details);
            for(ContractMortgageDetail detail:details){
                List<ContractGuaranty> institutions= contractGuarantyDao.selectInstitutions(dto.getProCode());
                jsonVo.setInstitutions(institutions);
            }
            /*附件信息表*/
            List<ProjectAttachment> projectAttaList = projectAttachmentDao.queryByWhere(dto.getProCode(), ProjectFileTypeEnum.FILE_TYPE51.getCode(), null);
            jsonVo.setFileAtt(setupProService.fileAttaListToArray(projectAttaList));
        }

        /*担保单位公司（下拉框）*/
        List<GuaranteeName> morName = contractPledgeDetailDao.queryGuaranteeName();
        jsonVo.setMorName(morName);

        return jsonVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RspVo edit(ContractMortgageDto contractMortgageDto, List<ContractMortgageDetail> detailList, List<ProjectAttachment> attachmentList, Integer submitType, AuthorizationVO vo) {
        String codes=codeGeneratorConfigService.generatorCode("cap_contract_mortgage");
        ContractMortgage contractMortgage=new ContractMortgage();
        BeanUtils.copyProperties(contractMortgageDto,contractMortgage);
        //判断id存不存在，存在就修改
        if(StringUtils.isNotEmpty(contractMortgageDto.getId())){
            //校验数据是否存在
            ContractMortgage tmpPi = contractMortgageDao.selectByPrimaryKey(contractMortgageDto.getId());
            if (tmpPi == null) return RspVo.getFailureResponse(400, "保证合同数据不存在");
            //判断审批状态
            if (org.apache.commons.lang.StringUtils.isNotBlank(tmpPi.getProcessStatus())
                    && (org.apache.commons.lang.StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), tmpPi.getProcessStatus())
                    || org.apache.commons.lang.StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS9.getCode(), tmpPi.getProcessStatus()))) {
                return RspVo.getFailureResponse(400, "审批状态不正确，操作失败");
            }
            contractMortgage.setUptBy(vo.getId());
            contractMortgage.setUptTime(new Date());
            //更新主表信息
            contractMortgageDao.updateByIdSelective(contractMortgage);
        }else {
            //新增主表信息
            contractMortgage.setCodes(codes);
            contractMortgage.setAddBy(vo.getId());
            contractMortgage.setAddTime(new Date());
            contractMortgageDao.insertSelective(contractMortgage);
        }


        //更新子表数据
        contractMortgageDetailDao.deleteByPrimaryKey(contractMortgage.getId());
        if (detailList != null && detailList.size() > 0) {
            for (ContractMortgageDetail pid : detailList) {
                pid.setCodes(codes);
                pid.setProCode(contractMortgage.getProCode());
                pid.setAddBy(vo.getCode());
                pid.setAddTime(new Date());
                pid.setContractMortgageId(contractMortgage.getId());
            }
            contractMortgageDetailDao.insertByBatch(detailList);

        }

        //更新附件信息
        projectAttachmentDao.deleteByWhere(contractMortgage.getProCode(), ProjectFileTypeEnum.FILE_TYPE51.getCode(), null);
        if (attachmentList != null && attachmentList.size() > 0) {
            projectAttachmentDao.insertBatch(attachmentList);
        }
        if (submitType == 1) {
            if (org.apache.commons.lang.StringUtils.isNotBlank(contractMortgage.getOaId())) {
                oaFlowService.finishOA(contractMortgage.getOaId());
            }

            //由于担保单位和公司数据过多
            ContractMortgageJsonVo jsonVo=queryDetailById(contractMortgage.getId());
            List<GuaranteeName> compNames = jsonVo.getMorName();
            List<ContractMortgageDetail> infos = jsonVo.getDetails();
            if (compNames != null && compNames.size() > 0 && infos != null && infos.size() > 0) {
                List<GuaranteeName> tmpList = new ArrayList<>();
                for (ContractMortgageDetail info : infos) {
                    if (info == null) continue;
                    for (GuaranteeName gn : compNames) {
                        if (gn == null) continue;
                        if (StringUtils.equals(gn.getId(), info.getMortgageComp())) {
                            tmpList.add(gn);
                            break;
                        }
                    }
                }
                jsonVo.setMorName(tmpList);
            } else {
                jsonVo.setMorName(null);
            }

            String detailJson= JSON.toJSONString(jsonVo);

            capProcessManageService.sendProcess(CapProcessDetailTypeEnum.PRO_NODE_TYPE12, detailJson, contractMortgage.getId(), contractMortgage.getProCode(), vo);
        }
        return RspVo.getSuccessResponse();

    }
}
